/**
 * 规划国土部门官网“矿业权评估报告”
 *  
 */
import { Base, Item } from '../base';
class lngtbck extends Base {
  constructor() {
    super();
    this.name = '规划国土部门官网(矿业权评估报告)';
    this.enabled = true;
    this.encode = "gb2312";
    this.debug = false;
    this.timeout = 1000000;
    this.collection = "lnxm";
    this.collectionShowName = "辽宁项目爬虫";
    this.keyField = "title";
  }
  getItems(pageIndex:number) {
    let num = pageIndex + 1;
    let url = null;
    if (pageIndex == 0) {
        url = `http://www.lgy.gov.cn/gsgg/kyqsc/ckqcrzrjggs/index.html`;
    }
    else {
        url = `http://www.lgy.gov.cn/gsgg/kyqsc/ckqcrzrjggs/index_${pageIndex}.html`;
    }
    let content = this.spider.getSync(url);
    let $ = this.cheerio.load(content);
    let result:Item[] = [];
    let that = this;
    try {
        $('.datapage-listshow ul li').each(function (index, ele) {
            let item = that.buildItem();
            let title = $(ele).find('a').text().trim();
            let uri = 'http://www.lgy.gov.cn/gsgg/kyqsc/ckqcrzrjggs' + $(ele).find('a').attr('href').substring(1);
            result.push((<any>that).getExtraItem(uri, title));
        });
    }
    catch (error) {
        console.error(error);
    }
    return this.doArray(result);
}
  getExtraItem(url:string, title:string) {
    let content = this.spider.getSync(url);
    let $ = this.cheerio.load(content);
    let item = this.buildItem();
    let flag=false;
    for (let i = 0; i < 5; i++) {
      let s = $('.MsoNormalTable').find('tr').eq(i).find('td');
      let l = s.length;
      if (l == 4) {
        flag=true;
        (<any>item)[s.eq(0).text().trim()] = s.eq(1).text().trim();
        (<any>item)[s.eq(2).text().trim()] = s.eq(3).text().trim();
      }
      else {
          //console.log(s.eq(0).text().trim()+"**********************************");
          (<any>item)[s.eq(0).text().trim()] = s.eq(1).text().trim();
      }
     
  }
    if(flag==false){
        //do nothing
    }else{
        (<any>item).url = url;
        item.source = this.name;
        item.title = title;
        return item;
    }
    
   
}
doArray(arrayCount:Item[]){
    for(var i = 0 ;i<arrayCount.length;i++)  
      {  
         if((<any>arrayCount[i]) == "" || typeof(arrayCount[i]) == "undefined")  
         {  
            arrayCount.splice(i,1);  
                  i= i-1;  
               
         }  
           
      }  
      return arrayCount;  
}
  getPageCount(): number {
    return 2;
  }
}
module.exports = new lngtbck();